<template>
  <div>
    <BaseSearch @exports="exports" :config="searchConfig" v-bind="form" ref="search"></BaseSearch>
    <BaseTable :columns="columns" v-bind="table"></BaseTable>
  </div>
</template>

<script>
import BaseSearch from '@/components/BaseSearch/index.vue'
import BaseTable from '@/components/BaseTable/index.vue'
import { FormTableMixin } from '@/mixins/form-table'
import http from '@/utils/request'
import { formattedAmount } from '@/utils/validator'
const service = async params => {
  const formatTime = value => {
    if (!value) return ''
    const date = new Date(value)
    const year = date.getFullYear()
    let month = date.getMonth() + 1
    let day = date.getDate()

    month = month < 10 ? '0' + month : month
    day = day < 10 ? '0' + day : day
    return `${year}-${month}-${day}`
  }
  let date_ = formatTime(params.statisticalDay ? params.statisticalDay : new Date())

  const data = {
    ascs: [],
    descs: [],
    limit: params.limit,
    current: params.current,
    statisticalDay: date_.substring(0, 4),
  }
  const { records, total } = await http.get('/operations/getAveragedayLoanList', {
    params: data,
  })
  return {
    data: records,
    total: total,
  }
}

export default {
  name: 'loanDay',
  mixins: [FormTableMixin(service)],
  components: {
    BaseSearch,
    BaseTable,
  },
  watch: {
    form: {
      handler(val, oldVal) {
        if (this.$refs['search']) {
          let day = this.formatTime(new Date())
          this.columns = [
            { label: '编号', prop: 'number', width: 60 },
            { label: '企业名称', prop: 'companyName' },
            {
              label: '用款金额（元）',
              prop: 'paymentAmount',
              render: (value, row) => {
                return <div>{formattedAmount(row.paymentAmount)}</div>
              },
            },
            {
              label: '贷款日期',
              prop: 'loanDate',
              render: (value, row) => {
                return <div>{row.loanDate ? this.formatTime(row.loanDate.replace(/T/g, ' ')) : '--'}</div>
              },
            },
            {
              label: '用款截止日',
              prop: 'paymentDeadline',
              render: (value, row) => {
                return <div>{row.paymentDeadline ? this.formatTime(row.paymentDeadline.replace(/T/g, ' ')) : '--'}</div>
              },
            },
            { label: '用款时间（截止时间：' + day + '）', prop: 'paymentDate' },
            { label: '状态', prop: 'state' },
            {
              label: '年日均贷款余额（元）',
              prop: 'averagedayLoanBalance',
              render: (value, row) => {
                return <div>{formattedAmount(row.averagedayLoanBalance)}</div>
              },
            },
            { label: '资方', prop: 'fund' },
          ]
          this.$refs['search'].submit()
        }
      },
      immediate: true,
      deep: true,
    },
  },
  data() {
    return {
      // 初始化时空白页
      searchConfig: [
        {
          component: 'date-picker',
          prop: 'statisticalDay',
          type: 'year',
          label: '统计年份',
          value: new Date(),
          placeholder: '请选择',
        },
      ],
      columns: [],
    }
  },
  methods: {
    formatTime(value) {
      if (!value) return ''
      const date = new Date(value)
      const year = date.getFullYear()
      let month = date.getMonth() + 1
      let day = date.getDate()

      month = month < 10 ? '0' + month : month
      day = day < 10 ? '0' + day : day
      return `${year}-${month}-${day}`
    },
    async exports() {
      let statisticalDay = this.formatTime(this.form.value.statisticalDay ? this.form.value.statisticalDay : new Date())
      const res = await http.get('/operations/export', {
        responseType: 'blob',
        params: {
          endTime: '',
          statisticalDay: statisticalDay.substring(0, 4),
          startTime: '',
          type: '4',
        },
      })
      let blob = new Blob([res.data], { type: 'application/vnd.ms-excel;charset=UTF-8' })
      let downloadElement = document.createElement('a')
      let href = window.URL.createObjectURL(blob) //创建下载的链接
      downloadElement.href = href
      downloadElement.download = '年日均贷款余额.xlsx' //下载后文件名
      document.body.appendChild(downloadElement)
      downloadElement.click() //点击下载
      document.body.removeChild(downloadElement) //下载完成移除元素
      window.URL.revokeObjectURL(href) //释放掉blob对象
    },
  },
}
</script>

<style lang="scss" scoped>
p.p-title {
  font-weight: bold;
  padding: 22px 0;
}
::v-deep {
  .el-range-separator {
    width: 6% !important;
  }
}
</style>
